<template>
  <!-- !楼层内容 -->
  <div class="room-info">
    <section class="header">
      <a-page-header
        :style="
          isLeftMenu
            ? 'padding: 10px 16px 8px 16px'
            : 'padding: 10px 16px 0px 16px'
        "
        :backIcon="false"
      >
        <template #title>
          <a-space>
            <BlIcon type="tree-fangjian" />
            <span> {{ roomDetail.room_name }} </span>
            <a-select
              v-model:value="currentRoomId"
              style="width: 120px; margin-left: 10px"
              @change="onCurrentRoomChange"
              :options="
                subRoomList.map((item) => ({
                  label: item.room_name,
                  value: item.id,
                }))
              "
              v-if="showSubRoomSelect && subRoomList.length > 0"
            >
            </a-select>
          </a-space>
        </template>
        <template #extra>
          <a-space :style="isModal ? 'padding-right: 50px' : ''">
            <a-button type="primary" ghost @click="editVisible = true">
              <template #icon>
                <FormOutlined />
              </template>
              编辑
            </a-button>

            <a-button
              type="primary"
              v-if="
                roomDetail.is_lock == 0 &&
                (roomDetail.room_status < 10 ||
                  roomDetail.contract_button == 1) &&
                !roomDetail.has_rent
              "
              @click="newContract"
            >
              <template #icon>
                <SolutionOutlined />
              </template>
              录入合同
            </a-button>

            <a-dropdown>
              <template #overlay>
                <a-menu @click="onOptMenuClick">
                  <a-menu-item key="merge" v-if="!roomDetail.parent_room_id">
                    <ForkOutlined />
                    合并
                  </a-menu-item>

                  <a-menu-item key="divide" v-if="!roomDetail.parent_room_id">
                    <SisternodeOutlined />
                    拆分
                  </a-menu-item>

                  <a-menu-item
                    key="procreate"
                    v-if="!roomDetail.parent_room_id"
                  >
                    <PartitionOutlined />
                    创建子房间
                  </a-menu-item>

                  <a-menu-item key="lock">
                    <LockOutlined />
                    {{ roomDetail.is_lock == 1 ? "取消锁定" : "锁定" }}
                  </a-menu-item>
                  <a-menu-item key="remove">
                    <DeleteOutlined />
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button>
                更多操作
                <DownOutlined />
              </a-button>
            </a-dropdown>
          </a-space>
        </template>
        <a-menu
          v-if="!isLeftMenu"
          :mode="menuMode"
          :selectedKeys="[currentMenu.id]"
          @select="onMenuSelect"
        >
          <a-menu-item v-for="item of menuList" :key="item.id">
            {{ item.name }}
          </a-menu-item>
        </a-menu>
      </a-page-header>
    </section>
    <section class="content">
      <a-menu
        v-if="isLeftMenu"
        :mode="menuMode"
        :selectedKeys="[currentMenu.id]"
        @select="onMenuSelect"
        class="left-menu"
      >
        <a-menu-item v-for="item of menuList" :key="item.id">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
      <div v-if="!pageLoading" class="content-box">
        <!-- 房源信息 -->
        <RoomContent v-show="currentAlias == 'roomInfo'" :detail="roomDetail" />
        <!-- 租客合同 -->
        <RoomContract
          v-if="currentAlias == 'ownerContract'"
          :detail="roomDetail"
          @close="modalClose"
          @newContract="newContract"
          @editOwner="editVisible = true"
        />
        <!-- 租客账单 -->
        <RoomBill
          v-if="currentAlias == 'ownerBill'"
          :detail="roomDetail"
          @close="modalClose"
        />
        <!-- 租客流水 -->
        <RoomBillTurnover
          v-if="currentAlias == 'ownerStream'"
          :detail="roomDetail"
          @close="modalClose"
        />
        <!-- 房东信息 -->
        <RoomProprietor
          v-if="currentAlias == 'roomOwner'"
          :detail="roomDetail"
          @close="modalClose"
        />
        <!-- 租客员工 -->
        <RoomMember
          v-if="currentAlias == 'ownerUser'"
          :detail="roomDetail"
          @close="modalClose"
        />
        <!-- 财务记录-->
        <RoomBillRecord
          v-if="currentAlias == 'billInfo'"
          :detail="roomDetail"
          @close="modalClose"
        />
        <!-- 备忘提醒  -->
        <RoomRemark
          v-if="currentAlias == 'roomOperate'"
          :detail="roomDetail"
          @close="modalClose"
        />

        <!-- 应用页面 -->
        <template v-for="appMenu of loadedAppMenu" :key="appMenu.id">
          <micro-app-org
            v-show="appMenu.app == currentAppName && appMenu.mounted"
            router-mode="state"
            style="height: 100%"
            :name="appMenu.app + appMenu.arrKey + appSuffix"
            :url=" isProduction ? `${locationUrl}/micro_apps/${appMenu.app}/` : devHttpMap[currentAppName] "
            :default-page="`#${defaultPageData[currentAppName]}`"
            :data=" $utils.getAppToChildData({ loadInfo: { villageId, buildId, layerId, roomId, currentOwnerId }, }) "
            @mounted="appMenu.mounted = true"
            @datachange="(e) => { handlePageChange(e); }"
          ></micro-app-org>
          <div class="spin-box" v-if="appMenu.app == currentAppName && !appMenu.mounted">
            <a-spin tip="加载中...">
            </a-spin>
          </div>
        </template>
      </div>
    </section>

    <!-- 编辑房源 -->
    <AddHouse
      v-if="editVisible"
      :visible="editVisible"
      :buildId="roomDetail.build_id"
      :villageId="villageId"
      :layerId="roomDetail.layer_id"
      :id="roomId"
      @cancel="editVisible = false"
      @success="onRoomEditSuccess"
    />

    <!-- 拆分房源 -->
    <DivideRoom
      :visible="divideVisible"
      :parentRoom="roomDetail"
      :maxRoomNumber="maxRoomNumber"
      @close="divideVisible = false"
      @success="onDivideRoomSuccess"
    />

    <!-- 合并房源 -->
    <MergeRoom
      :visible="mergeVisible"
      :detail="roomDetail"
      @close="mergeVisible = false"
      @success="onMergeRoomSuccess"
    />

    <!-- 锁定、取消锁定房源 -->
    <a-modal
      v-model:visible="lockVisible"
      :title="roomDetail.is_lock == 1 ? '取消锁定房源' : '锁定房源'"
      centered
      @ok="onRoomLockSuccess"
    >
      <a-textarea
        v-model:value="lockReason"
        :placeholder="
          roomDetail.is_lock == 1 ? '请输入取消锁定原因' : '请输入锁定原因'
        "
        :rows="4"
      />
    </a-modal>

    <!-- 创建子房间 -->
    <RoomProcreate
      :visible="procreateVisible"
      :parentRoom="roomDetail"
      @close="procreateVisible = false"
      @success="onRoomProcreateSuccess"
    />

    <!-- 录入合同 -->
    <SimpleContract
      :visible="contractVisible"
      :roomDetail="roomDetail"
      :id="fastContractId"
      :contractInfo="contractInfo"
      @closeDrawer="contractVisible = false"
    />

    <!-- 快速录入时审批中提示 -->
    <div ref="approveModal" class="approve-modal">
      <a-modal
        v-model:visible="addContractVisible"
        @ok="goNext"
        @cancel="closeTips"
        destroyOnClose
        :getContainer="approveModal"
      >
        <template #title>
          <div class="confirm-title">
            <ExclamationCircleOutlined
              :style="{
                color: '#faad14',
                marginRight: '10px',
                fontSize: '22px',
              }"
            />请注意
          </div>
        </template>
        <template #footer>
          <a-button @click="goApprove">查看审批</a-button>
          <a-button key="submit" type="primary" @click="goNext"
            >继续录入</a-button
          >
        </template>
        <p>当前房间有合同正在审批中，请谨慎操作。</p>
      </a-modal>
    </div>
  </div>
</template>
<script>
import {
  defineComponent,
  reactive,
  toRefs,
  watch,
  computed,
  createVNode,
  ref,
  onBeforeUnmount,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store";
import { BlIcon } from "bl-common-vue3";
import {
  DeleteOutlined,
  FormOutlined,
  DownOutlined,
  LockOutlined,
  ForkOutlined,
  SisternodeOutlined,
  SolutionOutlined,
  PartitionOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { MAIN_APP_NAMES } from "../../micro_apps/index";

import AddHouse from "../../views/village/SpaceManage/modules/AddHouse.vue";
import DivideRoom from "../../views/village/SpaceManage/modules/DivideRoom.vue";
import MergeRoom from "../../views/village/SpaceManage/modules/MergeRoom.vue";
import RoomProcreate from "../../views/village/SpaceManage/modules/RoomProcreate.vue";

import RoomContent from "./modules/RoomContent.vue";
import RoomContract from "./modules/RoomContract.vue";
import RoomBill from "./modules/RoomBill.vue";
import RoomProprietor from "./modules/RoomProprietor.vue";
import RoomMember from "./modules/RoomMember.vue";
import RoomRemark from "./modules/RoomRemark.vue";
import RoomBillRecord from "./modules/RoomBillRecord.vue";
import SimpleContract from "../contract/NewContract/SimpleContract.vue";
import RoomBillTurnover from "./modules/RoomBillTurnover.vue";

import { message, Modal } from "ant-design-vue";
import utils from "../../common/utils/utils";
import { useRouter, useRoute } from "vue-router";
import microApp from "@micro-zoe/micro-app";

// 渲染的组件映射 alias => components
const APP_COMPONENTS_MAP = {
  roomPropertyInfo: "villagePropertyInfo",
  roomWorkOrderInfo: "villageWorkOrderInfo",
  roomEnergyInfo: "villageEnergyInfo",
  roomIotInfo: "villageIotInfo",
  roomCarList: "roomCarList",
};

export default defineComponent({
  name: "RoomInfo",
  components: {
    BlIcon,
    DeleteOutlined,
    FormOutlined,
    RoomContent,
    AddHouse,
    DownOutlined,
    LockOutlined,
    ForkOutlined,
    SisternodeOutlined,
    PartitionOutlined,
    SolutionOutlined,
    DivideRoom,
    MergeRoom,
    RoomProcreate,
    RoomContract,
    RoomBill,
    RoomProprietor,
    RoomMember,
    RoomRemark,
    RoomBillRecord,
    SimpleContract,
    RoomBillTurnover,
    ExclamationCircleOutlined,
  },
  props: {
    // 调取页面
    pageFrom: {
      type: String,
      default: "",
    },
    // 展示类型 modal弹层展示 page页面内展示
    showType: {
      type: String,
      default: "modal",
    },
    // 菜单方向 horizontal  vertical
    menuMode: {
      type: String,
      default: "horizontal",
    },
    // 项目id
    villageId: {
      type: Number,
      default: 0,
    },
    // 楼宇id 可选
    buildId: {
      type: Number,
      default: 0,
    },
    // 楼层id 可选
    layerId: {
      type: Number,
      default: 0,
    },
    //   房源id
    roomId: {
      type: Number,
      default: 0,
    },
    // 子房间的父房间id
    parentRoomId: {
      type: Number,
      default: 0,
    },
    // 当前楼层最大房源编号 可选
    maxRoomNumber: {
      type: [Number, String],
      default: "",
    },
    // 是否可切换到该房间的子房间
    showSubRoomSelect: {
      type: Boolean,
      default: false,
    },
    appSuffix: {
      type: String,
      default: "",
    }
  },
  setup(props, { emit }) {
    const $router = useRouter();
    const ROUTE = useRoute();
    const approveModal = ref(null);

    const state = reactive({
      pageLoading: false,
      // 菜单
      menuList: [],
      currentMenu: {},
      //   房源详情
      roomDetail: {},
      // 编辑房源
      editVisible: false,
      // 展示应用页面
      showMicroPages: false,
      currentAppName: "",
      currentAlias: "",
      loadedAppMenu: [],
      currentAppComponent: "",

      // 房间操作
      divideVisible: false,
      mergeVisible: false,
      lockVisible: false,
      procreateVisible: false,
      lockReason: "",

      contractVisible: false,
      fastContractId: 0,
      contractInfo: {},

      subRoomList: [], //子房间下拉列表
      currentRoomId: 0,
      addContractVisible: false,
      contractData: {},

      currentOwnerId: 0
    });

    // 是否是弹框拉起
    const isModal = computed(() => props.showType == "modal");

    // 是否是左侧显示菜单
    const isLeftMenu = computed(() => props.menuMode == "vertical");

    /** 更多按钮点击 */
    const onOptMenuClick = (e) => {
      const { key } = e;
      switch (key) {
        case "remove":
          onRoomRemove();
          break;
        case "divide":
          onRoomDivide();
          break;
        case "merge":
          onRoomMerge();
          break;
        case "lock":
          onRoomLock();
          break;
        case "procreate":
          onRoomProcreate();
          break;
        default:
          break;
      }
    };

    /** 弹窗关闭 */
    const modalClose = () => {
      if (isModal.value) {
        emit("close");
      }
    };

    const villageType = computed(() => store.getters.buildingInfo.villageType);

    // 是否是子房间
    const isSubRoom = computed(() => {
      if (props.parentRoomId > 0 || props.roomId != state.roomDetail.id) {
        return true;
      } else {
        return false;
      }
    });

    /** 录入合同 */
    const newContract = () => {
      state.contractData = {};
      if (state.roomDetail.sub_room_count > 0) {
        Modal.warning({
          title: "提示",
          content: `该房间存在子房间，无法录入合同！`,
          centered: true,
        });
        return;
      }
      state.fastContractId = 0;
      // 验证是否有审批流程
      request
        .post("/org", "/contract/checkBuildProcess", {
          buildIds: [state.roomDetail.build_id],
        })
        .then((res) => {
          if (res.hasProcess) {
            if (villageType.value == "apartment") {
              // 公寓
              request
                .get("/org", "/contract/getEasyContractByRoom", {
                  build_id: state.roomDetail.build_id,
                  room_id: state.roomDetail.id,
                })
                .then((res) => {
                  if (
                    res.contractData &&
                    res.contractData.id &&
                    state.roomDetail?.has_rent
                  ) {
                    state.fastContractId = res.contractData.id;
                    state.contractInfo = res.contractData;
                  }
                  if (res.contractData?.approve_status == 1) {
                    // 有待审批的合同
                    state.contractData = res.contractData;
                    state.addContractVisible = true;
                  } else {
                    state.contractVisible = true;
                  }
                });
            } else {
              modalClose();
              let query = {
                room_id: state.roomDetail.id,
                village_id: props.villageId,
                layer_id: state.roomDetail.layer_id,
                build_id: state.roomDetail.build_id,
              };
              // 子房间特殊处理
              if (isSubRoom.value) {
                if (state.roomDetail.id == props.roomId) {
                  // 本身就是子房间
                  query.room_id = props.parentRoomId;
                  query.sub_room_id = state.roomDetail.id;
                } else {
                  // 父房间切换选择后的子房间
                  query.room_id = props.roomId;
                  query.sub_room_id = state.roomDetail.id;
                }
              }

              if (window.__MICRO_APP_ENVIRONMENT__) {
                let microAppUrl = `/contract/addContract?room_id=${query.room_id}${query.sub_room_id ? '&sub_room_id=' + query.sub_room_id : ''}&village_id=${query.village_id}&layer_id=${query.layer_id}&build_id=${query.build_id}`
                window.microApp.forceDispatch({
                  type: "SetMicroPages",
                  microInfo: {
                    microId: `org_add_contract_${query.room_id}${query.sub_room_id ? '_' + query.sub_room_id : ''}_${query.village_id}_${query.layer_id}_${query.build_id}`,
                    app: 'org',
                    name: `创建合同`,
                    url: microAppUrl,
                  }
                })
              }
             
            }
          } else {
            Modal.confirm({
              title: () => "提示",
              content: () => "您需要先添加合同新建审批流程才能创建合同哦~",
              icon: () => createVNode(ExclamationCircleOutlined),
              centered: true,
              okText: () => "前往",
              onOk() {
                utils.goProcessContract({type: "add"});
              },
            });
          }
        });
    };

    const closeTips = () => {
      state.addContractVisible = false;
    };
    const goApprove = () => {
      $router.push({
        name: "contractApproval",
        query: {
          approveId: state.contractData.approve_id,
          contractId: state.contractData.contract_id,
        },
      });
      closeTips();
    };

    const goNext = () => {
      state.contractVisible = true;
      closeTips();
    };

    /** 编辑房源 */
    const onRoomEditSuccess = () => {
      state.editVisible = false;
      getRoomDetail(true);
    };

    /** 锁定房源 */
    const onRoomLock = () => {
      if (state.roomDetail.sub_room_count > 0) {
        Modal.warning({
          title: "提示",
          content: `该房间存在子房间，无法锁定`,
          centered: true,
        });
        return;
      }
      state.lockReason = "";
      state.lockVisible = true;
    };
    const onRoomLockSuccess = () => {
      if (!state.lockReason) {
        message.warning("请输入原因~");
        return;
      }
      request
        .post("/village", "/project/room/lock", {
          id: state.roomDetail.id,
          village_id: state.roomDetail.village_id,
          lock_reason: state.lockReason,
          is_lock: state.roomDetail.is_lock == 1 ? 0 : 1,
          needMsg: true,
        })
        .then((res) => {
          message.success(res.msg || "操作成功");
          state.lockVisible = false;
          getRoomDetail(true);
        });
    };

    /** 拆分房间 */
    const onRoomDivide = () => {
      const disabledMsg = getDisabledTip();
      if (disabledMsg) {
        Modal.warning({
          title: "提示",
          content: `${disabledMsg}，无法拆分！`,
          centered: true,
        });
        return;
      }
      if (state.roomDetail.sub_room_count > 0) {
        Modal.warning({
          title: "提示",
          content: `该房间存在子房间，无法拆分！`,
          centered: true,
        });
        return;
      }
      state.divideVisible = true;
    };
    const onDivideRoomSuccess = () => {
      state.divideVisible = false;
      getRoomDetail(true);
      updateTree();
    };

    /** 合并房间 */
    const onRoomMerge = () => {
      const disabledMsg = getDisabledTip();
      if (disabledMsg) {
        Modal.warning({
          title: "提示",
          content: `${disabledMsg}，无法合并！`,
          centered: true,
        });
        return;
      }
      if (state.roomDetail.sub_room_count > 0) {
        Modal.warning({
          title: "提示",
          content: `该房间存在子房间，无法合并！`,
          centered: true,
        });
        return;
      }
      state.mergeVisible = true;
    };
    const onMergeRoomSuccess = () => {
      state.mergeVisible = false;
      if (isModal.value) {
        modalClose();
        updateTree();
      } else {
        emit("remove");
      }
    };

    /** 创建子房间 */
    const onRoomProcreate = () => {
      const disabledMsg = getDisabledTip();
      if (disabledMsg) {
        Modal.warning({
          title: "提示",
          content: `${disabledMsg}，无法创建子房间！`,
          centered: true,
        });
        return;
      }
      state.procreateVisible = true;
    };

    const onRoomProcreateSuccess = () => {
      state.procreateVisible = false;
      getRoomDetail(true);
      updateTree();
    };

    // 更新页面左侧树
    const updateTree = () => {
      if (props.pageFrom == "ManagementCenter") {
        store.dispatch("RefreshMCTree", {
          villageId: state.roomDetail.village_id,
          buildId: state.roomDetail.build_id,
          layerId: state.roomDetail.layer_id,
        });
      }
    };

    // 获取无法拆分、合并的文案
    const getDisabledTip = () => {
      if (!state.roomDetail.rental_area) {
        return "当前房间还未维护计租面积等面积值";
      }
      if (state.roomDetail.room_status != 0) {
        return "当前房间非空置状态";
      }
      if (state.roomDetail.is_lock == 1) {
        return "当前房间已锁定";
      }
    };

    /** 删除房源 */
    const onRoomRemove = () => {
      utils.modalConfirm({
        content: `确认删除本房源吗？`,
        centered: true,
        okType: "danger",
        onOk: () => {
          request
            .del("/village", "/project/room", {
              village_id: props.villageId,
              id: state.roomDetail.id,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "删除成功");
              emit("remove");

              // 如果当前房间号改变，则是切换的子房间
              if (props.roomId !== state.roomDetail.id) {
                init();
              }
            });
        },
      });
    };

    /** 获取子房间列表 */
    const getSubRooms = () => {
      request
        .get("/village", "/project/room/all", {
          village_id: props.villageId,
          layer_id: state.roomDetail.layer_id,
          parent_room_id: state.roomDetail.id,
        })
        .then((res) => {
          state.subRoomList = res.list;
          state.subRoomList.unshift({
            id: state.roomDetail.id,
            room_name: state.roomDetail.room_name,
          });
          // 默认选中值为当前房间id
          state.currentRoomId = state.roomDetail.id;
        });
    };

    /** 获取房间详情 */
    const getRoomDetail = (refresh = false, roomId) => {
      request
        .get("/village", "/project/room/get", {
          village_id: props.villageId,
          id: roomId ? roomId : props.roomId,
        })
        .then((res) => {
          state.roomDetail = res.detail;
          if (refresh) {
            emit("onChange", {
              name: state.roomDetail.room_name,
              roomDetail: state.roomDetail,
            });
          }

          // 如果有子房间
          if (res.detail && res.detail.sub_room_count) {
            getSubRooms();
          }
        })
        .finally(() => {
          state.pageLoading = false;
        });
    };

    /** 菜单选中 */
    const onMenuSelect = (menu) => {
      const { key } = menu;
      state.currentMenu = state.menuList.find((item) => item.id == key);
      if (
        !state.currentMenu.app ||
        MAIN_APP_NAMES.includes(state.currentMenu.app)
      ) {
        // 主应用内菜单
        state.currentAppName = "";
        state.currentAlias = state.currentMenu.alias;
        state.currentAppComponent = "";
      } else {
        // 显示子应用内容
        state.currentAppName = state.currentMenu.app;
        state.currentAlias = `${state.currentMenu.alias}?villageId=${props.villageId}&buildId=${state.roomDetail.build_id}&layerId=${state.roomDetail.layer_id}&roomId=${state.roomDetail.id}`;
        const index = state.loadedAppMenu.findIndex(
          (it) => it.id == state.currentMenu.id
        );
        if (index == -1) {
          state.loadedAppMenu.push(state.currentMenu);
        }
        state.currentAppComponent =
          APP_COMPONENTS_MAP[state.currentMenu.alias] ||
          state.currentMenu.alias;

        // 存储当前房间信息，子应用使用
        let currentRoomInfo = {
          villageId: props.villageId,
          buildId: state.roomDetail.build_id,
          layerId: state.roomDetail.layer_id,
          roomId: state.roomDetail.id,
          sub_room_count: state.roomDetail.sub_room_count,
        };

        // 子房间特殊处理
        if (isSubRoom.value) {
          if (state.roomDetail.id == props.roomId) {
            // 本身就是子房间
            currentRoomInfo.roomId = props.parentRoomId;
            currentRoomInfo.subRoomId = props.roomId;
          } else {
            // 父房间切换选择后的子房间
            currentRoomInfo.roomId = props.roomId;
            currentRoomInfo.subRoomId = state.roomDetail.id;
          }
        }

        console.log(currentRoomInfo);
        store.dispatch("SetCurrentRoom", currentRoomInfo);
      }
    };

    /** 获取导航菜单 */
    const getMenuList = () => {
      if (state.menuList.length) {
        onMenuSelect({ key: state.menuList[0].id });
        return;
      }
      request
        .get("/village", "/rentControl/menuList", {
          menu_type: "room",
        })
        .then((res) => {
          state.menuList = res.list;
          onMenuSelect({ key: state.menuList[0].id });
        });
    };

    const handlePageChange = (e) => {
      const data = e?.detail?.data;
      window.microApp.forceDispatch({
        ...data,
      });
    };

    const locationUrl = location.origin;

    const devHttpMap = {
      org: "http://localhost:4001/",
      workVisitor: "http://localhost:4005/",
      workNotice: "http://localhost:4006/",
      workPark: "http://localhost:4007/",
      workEnergy: "http://localhost:4008/",
      workProperty: "http://localhost:4009/",
      workApproval: "http://localhost:4010/",
      workTask: "http://localhost:4011/",
      workSchedule: "http://localhost:4012/",
      workOrder: "http://localhost:4013/",
      workMeetingRoom: "http://localhost:4014/",
      workPatrol: "http://localhost:4015/",
      workCuPage: "http://localhost:4016/",
      workIOT: "http://localhost:4017/",
      workThird: "http://localhost:4018/",
      workForum: "http://localhost:4019/",
      shop: "http://localhost:4020/",
      workAI: "http://localhost:4021/",
      workWiki: "http://localhost:4022/",
      workHr: "http://localhost:4023/",
      workMail: "http://localhost:4024/",
      thirdSichuanPolice: "http://localhost:4025/",
    };

    const defaultPageData = {
      workProperty: "/property/Inventory",
      workOrder: "/order/workOrderDynamics",
      workIOT: "/main/villageIotInfo",
      workEnergy: "/energyConsumption",
      workPark: "/roomList/index",
    };

    const isProduction = !utils.isEnv();

    const UnloadApp = () => {
      state.loadedAppMenu.forEach((item) => {
        microApp.unmountApp(item.app + item.arrKey + props.appSuffix, { destroy: true, clearAliveState: true })
      });
    };

    const init = () => {
      UnloadApp()
      if (!props.roomId) {
        return;
      }
      state.pageLoading = true;
      getMenuList();
      getRoomDetail();
    };

    onBeforeUnmount(() => {
      UnloadApp();
    });

    watch(
      () => props.roomId,
      () => {
        init();
      }
    );

    watch(
      () => ROUTE.name,
      () => {
        state.contractVisible = false;
        modalClose();
      }
    );

    init();

    const onCurrentRoomChange = (value) => {
      getRoomDetail(false, value);
    };

    const getOwnerListByRoomId = () => {
      // 选择房间
      request
        .get("/org", "/owner/ownerListByRoomId", {
          build_id: state.roomDetail.build_id,
          room_id: state.roomDetail.id,
        })
        .then((res) => {
          if (res.list && res.list.length > 0) {
            state.currentOwnerId = res.list[0].id
            store.commit("SET_ADD_TURNOVER_OWNER_ID", res.list[0].id);
          } else {
            state.currentOwnerId = 0
            store.commit("SET_ADD_TURNOVER_OWNER_ID", 0);
          }
          store.commit("SET_ADD_TURNOVER_VISIBLE", true);
        });
    }

    watch(
      ()=>state.roomDetail.id,
      (val)=>{
          if (val) {
            getOwnerListByRoomId()
          } else {
            state.currentOwnerId = 0
            store.commit("SET_ADD_TURNOVER_OWNER_ID", 0);
            store.commit("SET_ADD_TURNOVER_VISIBLE", true);
          }
      }
    )

    return {
      isModal,
      isLeftMenu,
      ...toRefs(state),
      onMenuSelect,
      onRoomEditSuccess,
      newContract,
      onOptMenuClick,
      onDivideRoomSuccess,
      onMergeRoomSuccess,
      onRoomLockSuccess,
      onRoomProcreateSuccess,
      modalClose,

      onCurrentRoomChange,
      isSubRoom,
      goNext,
      goApprove,
      closeTips,
      approveModal,
      locationUrl,
      devHttpMap,
      defaultPageData,
      isProduction,
      handlePageChange,
    };
  },
});
</script>
<style lang="less" scoped>
@menuWidth: 120px;
.room-info {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  .content {
    flex: 1;
    overflow: hidden;
    display: flex;
    background-color: #f7f7f7;
    .left-menu {
      min-width: @menuWidth;
      max-width: @menuWidth;
      height: 100%;
      overflow: hidden auto;
      background-color: #fff;
      margin-top: -4px;
    }

    .content-box {
      flex: 1;
      height: 100%;
      overflow: hidden auto;
      padding: 6px;
      background-color: #f7f7f7;
        .spin-box {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
         }
    }
  }
}
.confirm-title {
  display: flex;
  align-items: center;
}
.approve-modal {
  :deep(.ant-modal-header) {
    border-bottom: none !important;
  }
  :deep(.ant-modal-footer) {
    border-top: none !important;
  }
}
:deep(.ant-table-sticky-holder) {
  top: -6px !important;
}
</style>
